package com.iye.puretennis.custom;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import com.iye.puretennis.domain.Location;
import com.iye.puretennis.domain.UserToken;
import com.iye.puretennis.helper.Constant;
import com.iye.puretennis.helper.DBManager;
import com.iye.puretennis.helper.ServerAccessHelper;
import com.iye.puretennis.utils.TimeUtils;

import java.io.IOException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: jing wu
 * Date: 2014/12/23
 * Time: 11:06
 */
public class LocationHandler implements LocationListener {

    public static int REFRESH_TIME = 60000;

    public static int REFRESH_DISTANCE = 100;

    private Context context;

    private Timer timer;

    private DBManager dbManager;

    public LocationHandler(Context context, DBManager dbManager) {
        this.context = context;
        this.dbManager = dbManager;
    }

    public void updateLocation(final String token) {

        final android.location.Location location = getLocation();

        if (location != null) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    doUpdate(token, location);
                }
            });

        }
        timer = new Timer(true);
        TimerTask task = new TimerTask() {
            public void run() {
                android.location.Location newLocation = getLocation();
                doUpdate(token, newLocation);
            }
        };
        timer.schedule(task, new Date(), REFRESH_TIME);

    }

    private android.location.Location getLocation() {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        String provider;

        String gpsProvider = LocationManager.GPS_PROVIDER;
        String networkProvider = LocationManager.NETWORK_PROVIDER;
        if (locationManager.isProviderEnabled(gpsProvider)) {
            provider = gpsProvider;
        } else if (locationManager.isProviderEnabled(networkProvider)) {
            provider = networkProvider;
        } else {
            openGPS(context);
            provider = gpsProvider;
        }

        locationManager.requestLocationUpdates(provider, REFRESH_TIME, REFRESH_DISTANCE, this);

        return locationManager.getLastKnownLocation(provider);
    }

    private void doUpdate(String token, android.location.Location location) {
        String result = ServerAccessHelper.updateLocation(token, convertLocation(context, location));
        if (!Constant.RESPONSE_BADLY.equals(result)) {
            dbManager.updateUserLocation(location.getLatitude() + "", location.getLongitude() + "");
        }
    }


    public void stopTimer() {
        if (timer != null) {
            timer.cancel();
        }
    }


    private Location convertLocation(Context context, android.location.Location location) {
        Location currentLocation = null;


        if (location != null) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            String cityName = null;
            List<Address> addresses;
            try {
                Geocoder gcd = new Geocoder(context, Locale.getDefault());
                addresses = gcd.getFromLocation(latitude, longitude, 1);
                if (addresses.size() > 0) {
                    cityName = addresses.get(0).getLocality();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            currentLocation = new Location(cityName, String.valueOf(latitude), String.valueOf(longitude), TimeUtils.now());
        }

        return currentLocation;
    }

    public void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }

    public void stopGPS() {

        stopTimer();

        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        locationManager.removeUpdates(this);


    }

    @Override
    public void onLocationChanged(final android.location.Location location) {

    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }
}
